package com.ruoyi.web.controller.student;

import com.ruoyi.common.core.domain.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;

/**
 * 文件上传Controller
 *
 * @author wangzebing
 * @date 2025-03-20
 */
@RestController
@RequestMapping("/basisUpload")
public class uploadController {
    @Value("${upload.path}")
    private String uploadFilePath;

    @PostMapping("/upload")
    public R uploadFile(@RequestParam("file") MultipartFile file,String type){

        if (file.isEmpty()) {
            return R.fail("上传失败：文件为空");
        }

        try {
            Path uploadPath = Paths.get(uploadFilePath);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名，防止冲突和路径遍历
            String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
            String fileName = UUID.randomUUID().toString() + "_" + originalFileName;

            // 保存文件到指定路径
            Path filePath = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            Map<String, Object> map = new HashMap<>();
            System.out.println(filePath);
            map.put("filePath",filePath.toString());
            map.put("type",type);
            return R.ok(map);
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail("上传失败：" + e.getMessage());
        }
    }


    @PostMapping("/uploadTeacher")
    public ResponseEntity<Map<String,Object>> uploadFile(@RequestParam("file") MultipartFile file){
        Map<String, Object> map = new HashMap<>();
        String fileName = "";

            if (file.isEmpty()) {
                map.put("msg","上传失败：文件为空");
                map.put("fileName","");
                return ResponseEntity.badRequest().body(map);
            }

            try {
                Path uploadPath = Paths.get(uploadFilePath);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }

                // 生成唯一文件名，防止冲突和路径遍历
                String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
                fileName = UUID.randomUUID().toString() + "_" + originalFileName;

                // 保存文件到指定路径
                Path filePath = uploadPath.resolve(fileName);
                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                map.put("msg","文件上传成功");
                map.put("fileName",fileName);
                return ResponseEntity.ok(map);

        } catch (IOException e) {
            e.printStackTrace();
            map.put("msg", "上传失败：" + e.getMessage());
            map.put("fileName", "");
            return ResponseEntity.internalServerError().body(map);
        }

    }


    @PostMapping("/studentUpload")
    public ResponseEntity<Map<String, Object>> studentUpload(@RequestParam("file") MultipartFile file, String type) {
        Map<String, Object> map = new HashMap<>();
        if (file.isEmpty()) {
            map.put("msg", "上传失败：文件为空");
            map.put("filePath", "");
            return ResponseEntity.badRequest().body(map);
        }
        String content="";
        Path path = null;
        try {
            switch (type) {
                case "0":
                    path = saveFile(file, ".txt");
                    content = readCityFile(path.toString());
                    break;
                case "1":
                    path= saveFile(file,".mp3");
                    break;
                case "2":
                    path = saveFile(file, ".txt");
                    content = readCityFile(path.toString());
                    break;
            }
            map.put("msg", content);
            map.put("filePath",path.toString());

            return ResponseEntity.ok(map);
        } catch (IOException e) {
            map.put("msg", "上传失败：" + e.getMessage());
            map.put("filePath", "");
            return ResponseEntity.internalServerError().body(map);
        }
    }
    @PostMapping("/downLoadFile")
    public void downLoadFile(HttpServletResponse response,String filePath) throws IOException{
        File file = new File(filePath);
        String fileName = file.getName();
        String[] split = fileName.split("\\.");
        if(!split[1].equals("mp3")){
            response.setCharacterEncoding("GB2312");
        }
        response.setContentType("application/octet-stream");

        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        try (InputStream inputStream = new FileInputStream(filePath);
            OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }


    /**
     * 保存文件
     *
     * @param file
     * @throws IOException
     */
    public Path saveFile(MultipartFile file,String suffix) throws IOException {
        Path uploadPath = Paths.get(uploadFilePath);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        // 生成唯一文件名，防止冲突和路径遍历
        String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
        String[] split = originalFileName.split("\\.");
        String fileName = UUID.randomUUID().toString() + "_" + split[0] + suffix;
        // 保存文件到指定路径
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        return filePath;
    }

    private String readCityFile(String  path) {
        List<String> lines = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "GB2312"));
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line+"\n");
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(lines);

    }
}